# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

from optparse import OptionParser
from cve_ease import activate_session
import logging

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def cve_ease_status():
    import dbus
    sysbus = dbus.SystemBus()
    systemd1 = sysbus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager')
    job = manager.GetUnitFileState('cve-ease.timer')
    print(" * On-boot status cve-ease.timer:", job)
    manager.Reload()
    try:
        unit = manager.GetUnit('cve-ease.timer')
    except Exception:
        print(" * Active cve-ease.timer: dead")
        return
    unit_object = sysbus.get_object('org.freedesktop.systemd1', unit)
    prop_unit = dbus.Interface(unit_object, 'org.freedesktop.DBus.Properties')

    active_state = prop_unit.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
    sub_state = prop_unit.Get('org.freedesktop.systemd1.Unit', 'SubState')
    print(" * Active cve-ease.timer:", active_state, sub_state)


def cve_ease_start():
    import dbus
    sysbus = dbus.SystemBus()
    systemd1 = sysbus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager')
    manager.Reload()
    job = manager.EnableUnitFiles(['cve-ease.timer'], False, True)
    print(" * Enable cve-ease.timer:", job)
    job = manager.StartUnit('cve-ease.timer', 'fail')
    print(" * Start cve-ease.timer:", job)


def cve_ease_kill():
    import dbus
    sysbus = dbus.SystemBus()
    systemd1 = sysbus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager')
    job = manager.StopUnit('cve-ease.timer', 'fail')
    print(" * Stop cve-ease.timer:", job)
    job = manager.DisableUnitFiles(['cve-ease.timer'], False)
    print(" * Disable cve-ease.timer:", job)
    manager.Reload()


def cve_ease_restart():
    cve_ease_kill()
    cve_ease_start()


def handle_service(gconfig, db_session, args):
    """[basic] Service manager"""

    """
    org.freedesktop.systemd1 — The D-Bus interface of systemd
    reference: https://dbus.freedesktop.org/doc/dbus-python/dbus.html
               https://ggargblogs.wordpress.com/2020/09/06/using-dbus-api-in-python-for-managing-services-in-linux/
               https://manpages.ubuntu.com/manpages/impish/man5/org.freedesktop.systemd1.5.html
    :param gconfig:
    :param db_session:
    :param args:
    :return:
    """
    usage = "usage: %prog service <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-k', '--kill', dest='kill', action='store_true', default=False,
                      help='kill cve-ease service')
    parser.add_option('-r', '--restart', dest='restart', action='store_true', default=False,
                      help='restart cve-ease service')
    parser.add_option('-s', '--status', dest='status', action='store_true', default=False,
                      help='get cve-ease service status')
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False,
                      help='show verbose output')

    (options, args) = parser.parse_args(args)

    session = activate_session(db_session, gconfig)
    if gconfig.debug:
        print(" * active sql session")

    if options.status:
        cve_ease_status()
    elif options.kill:
        cve_ease_kill()
    elif options.restart:
        cve_ease_restart()
    else:
        parser.print_help()
